﻿using System;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Atmk.WaterMeter.MIS.Controllers
{
    /// <summary>
    /// 角色权限管理
    /// </summary>
    [Authorize]
    public class RolesController : BaseApiController //BaseCrudApiController<Role>
    {
        private static ILogger<RolesController> _logger;
        private readonly IRolesLogic _rolesLogic;

        /// <inheritdoc />
        public RolesController(ILogger<RolesController> logger, IRolesLogic rolesLogic
        )
        {
            _logger = logger;
            _rolesLogic = rolesLogic;
        }

        /// <summary>
        /// 查询所有角色数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/System/SelectRoles")]
        public IActionResult SelectRoles()
        {
            try
            {
                var list = _rolesLogic.SelectRoles();
                return Ok(
                    new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            list
                        }
                    });
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取角色数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        /// 添加角色信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/System/Roles/")]
        public IActionResult AddRoles([FromBody] dynamic obj)
        {
            try
            {
                var result = _rolesLogic.AddRoles(obj, out string exception,out string id);
                if (result)
                    return Ok(
                        new
                        {
                            errcode = 0,
                            msg = "ok",
                            id
                        });
                _logger.LogError(exception);
                return Ok(
                    new
                    {
                        errcode = 1,
                        msg = $"添加角色数据错误,RolesLogic.AddRoles:{exception}",
                        id
                    });
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"添加角色数据错误,错误:{e.Message}",
                    id=""
                });
            }
        }

        /// <summary>
        /// 修改角色信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/System/Roles/Update")]
        public IActionResult EditRoles([FromBody] dynamic obj)
        {
            try
            {
                var result = _rolesLogic.UpdateRoles(obj, out string exception);
                if (result)
                    return Ok(
                        new
                        {
                            errcode = 0,
                            msg = "ok"
                        });
                _logger.LogError(exception);
                return Ok(
                    new
                    {
                        errcode = 1,
                        msg = $"修改角色数据错误,RolesLogic.UpdateRoles:{exception}"
                    });
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"修改角色数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        /// 删除角色信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/System/Roles/Delete")]
        public IActionResult DeleteRoles([FromBody] dynamic obj)
        {
            try
            {
                var id = obj.id.ToString();
                var result = _rolesLogic.DeleteRole(id, out string exception);
                if (result)
                    return Ok(
                        new
                        {
                            errcode = 0,
                            msg = "ok"
                        });
                _logger.LogError(exception);
                return Ok(
                    new
                    {
                        errcode = 1,
                        msg = $"删除角色数据错误,RolesLogic.UpdateRoles:{exception}"
                    });
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"删除角色数据错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        /// 获取指定角色下的权限信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/System/Auth/{id}")]
        public IActionResult SelectParmissions(string id)
        {
            try
            {
                var result = _rolesLogic.SelectParmissions(id);
                return Ok(
                    new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = result
                    });
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取角色权限错误,错误:{e.Message}"
                });
            }
        }

        /// <summary>
        /// 修改角色信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/System/Auth/Update")]
        public IActionResult EditParmissions([FromBody] dynamic obj)
        {
            try
            {
                var id = obj.id.ToString();
                var authList = obj.authList.ToString();
                var result = _rolesLogic.UpdateParmissions(id, authList, out string exception);
                if (!result)
                {
                    return Ok(
                        new
                        {
                            errcode = 1,
                            msg = $"修改权限数据错误,RolesLogic.UpdateParmissions:{exception}"
                        });
                }

                return Ok(
                    new
                    {
                        errcode = 0,
                        msg = "ok"
                    });
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"修改权限数据错误,错误:{e.Message}"
                });
            }
        }
        ///// <inheritdoc />
        ///// <summary>
        ///// 查询角色信息
        ///// </summary>
        ///// <param name="sortOrder">排序字段 字段名 或 小写字段名_desc </param>
        ///// <param name="currentFilter">筛选字段</param>
        ///// <param name="searchString">筛选字段的关键字</param>
        ///// <param name="page">页数</param>
        ///// <returns></returns>
        //[HttpPost]
        //public override IActionResult Select(string sortOrder,
        //    string currentFilter,
        //    string searchString,
        //    int? page)
        //{
        //    var repository = new RolesRepository();
        //    var results = repository.FindIndex<Role>(sortOrder, currentFilter, searchString, page);
        //    return Ok(new
        //    {
        //        status = 1,
        //        results,
        //        results.Result.Count,
        //        results.Result.PageIndex,
        //        results.Result.TotalPages,
        //        results.Result.HasNextPage,
        //        results.Result.HasPreviousPage
        //    });
        //}

        ///// <inheritdoc />
        ///// <summary>
        ///// 添加角色信息
        ///// </summary>
        ///// <param name="entities"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public override IActionResult Insert([FromBody] params Role[] entities)
        //{
        //    if (entities == null)
        //        return Ok(new { status = 0, result = "添加失败，获取实体类为空" });
        //    var entity = entities.ToArray();
        //    var repository = new RolesRepository();
        //    if (entity.Length != 1) return Ok(new {status = 0, result = "没有添加多角色数据添加功能"});
        //    var result = repository.Add(entity[0]);
        //    return Ok(new {status = 1, result });
        //}

        ///// <inheritdoc />
        ///// <summary>
        ///// 删除角色
        ///// </summary>
        ///// <param name="guidStrings"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public override IActionResult Delete([FromBody] params string[] guidStrings)
        //{
        //    if (guidStrings == null)
        //        return Ok(new { status = 0, result = "删除失败，获取实体类为空" });
        //    var repository = new RolesRepository();
        //    //根据ID获取所有实体类集合
        //    var entitis = repository.FindAll<Role>().Where(e => e.RecordState == RecordStateEnum.Normal);
        //    var delentitis = entitis.Where(e => guidStrings.Contains(e.Id.ToString()));
        //    //执行删除
        //    var result = repository.Delete(delentitis.ToArray());
        //    return Ok(new { status = 1, result });
        //}
        ///// <inheritdoc />
        ///// <summary>
        ///// 修改角色信息
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //[CustomRoute(ApiVersions.v1, nameof(Update))]
        //public override IActionResult Update([FromBody] params Role[] entitis)
        //{
        //    if (entitis == null)
        //        return Ok(new { status = 0, result = "删除失败，获取实体类为空" });
        //    var entity = entitis.ToArray();
        //    var repository = new RolesRepository();
        //    var result = repository.Update(entity);
        //    return Ok(new { status = 1, result });
        //}

        ///// <summary>
        ///// 彻底删除信息--仅测试用
        ///// </summary>
        ///// <param name="entitis"></param>
        ///// <returns></returns>
        //[HttpPost]
        //[CustomRoute(ApiVersions.v1, nameof(DeleteClear))]
        //public IActionResult DeleteClear([FromBody] params Role[] entitis)
        //{
        //    if (entitis == null)
        //        return Ok(new { status = 0, result = "删除失败，获取实体类为空" });
        //    var entity = entitis.ToArray();
        //    var repository = new RolesRepository();
        //    var change = repository.Remove(entity);
        //    return Ok(new { status = 1, change });
        //}
    }
}